package com.mdd.front.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.response.AlipayFundAuthOperationDetailQueryResponse;
import com.alipay.api.response.AlipayFundAuthOrderAppFreezeResponse;
import com.alipay.api.response.AlipayUserAgreementPageSignResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mdd.common.entity.AlipayRoyaltyAccountInfo;
import com.mdd.common.entity.OrderFlowInfo;
import com.mdd.common.entity.agreement.AlipayAuthOrderFreeze;
import com.mdd.common.entity.agreement.AlipaySignUserAgreementRecord;
import com.mdd.common.entity.agreement.RiskControl;
import com.mdd.common.entity.order.OrderInfo;
import com.mdd.common.entity.order.OrderItem;
import com.mdd.common.entity.user.User;
import com.mdd.common.enums.auth.AuthStatusEnum;
import com.mdd.common.enums.auth.FundAuthFreezeStatus;
import com.mdd.common.enums.order.type.OrderFlowTypeEnum;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.AlipayRoyaltyAccountInfoMapper;
import com.mdd.common.mapper.OrderFlowInfoMapper;
import com.mdd.common.mapper.auth.AlipayAuthOrderFreezeMapper;
import com.mdd.common.mapper.order.OrderInfoMapper;
import com.mdd.common.mapper.order.OrderItemMapper;
import com.mdd.common.mapper.risk.RiskControlMapper;
import com.mdd.common.mapper.sign.AlipaySignUserAgreementRecordMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.util.CodeUtils;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.IAuthOrderService;
import com.mdd.front.vo.agreement.AlipayAuthOrderFreezeVo;
import com.mdd.front.vo.agreement.AlipaySignUserAgreementRecordVo;
import com.mdd.front.vo.agreement.UserSignVo;
import com.mdd.front.vo.order.OrderIdValidate;
import com.mdd.product.entity.LeasingSchemeDetails;
import com.mdd.product.mapper.LeasingSchemeDetailsMapper;
import com.mdd.service.agreement.UserAgreementService;
import com.mdd.service.auth.PreAuthorizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

import static com.mdd.common.enums.auth.FundAuthFreezeStatus.FUND_AUTH_UNFREEZE;

/**
 * <p>
 * {@code @Description}
 * {@code @Author} 幻速
 * {@code @Date} 2023/11/2 10:01
 **/
@Service
@Slf4j
public class AuthOrderServiceImpl implements IAuthOrderService {
    @Resource
    UserAgreementService userAgreementService;
    @Resource
    PreAuthorizationService preAuthorizationService;
    @Resource
    RiskControlMapper riskControlMapper;
    @Resource
    AlipaySignUserAgreementRecordMapper alipaySignUserAgreementRecordMapper;
    @Resource
    AlipayAuthOrderFreezeMapper alipayAuthOrderFreezeMapper;
    @Resource
    OrderInfoMapper orderInfoMapper;
    @Resource
    OrderItemMapper orderItemMapper;
    @Resource
    LeasingSchemeDetailsMapper leasingSchemeDetailsMapper;
    @Resource
    AlipayRoyaltyAccountInfoMapper alipayRoyaltyAccountInfoMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    OrderFlowInfoMapper orderFlowInfoMapper;
    @Resource
    DefaultAlipayClient defaultAlipayClient;
    String notifyAuthUrl="https://www.yixiutong.cn/rtadmin/api/notify/callback.htm";
    String notifyAgreementUrl= "https://www.yixiutong.cn/rtadmin/api/notify/callback.htm";

//    @PostConstruct
//    public void initAlipayClient() throws AlipayApiException {
//        TripartiteAppConfig aliPayConfig = userTripartiteAppConfigService.getAliPayConfig("1");
//        if (!Objects.isNull(aliPayConfig) && StringUtils.hasText(aliPayConfig.getAppId())) {
//            AlipayConfig config = new AlipayConfig();
//            config.setAppId(aliPayConfig.getAppId());
//            config.setPrivateKey(aliPayConfig.getPrivateKey());
//            config.setAlipayPublicKey(aliPayConfig.getAlipayPublicKey());
//            config.setSignType(aliPayConfig.getSignType());
//            config.setServerUrl("https://openapi.alipay.com/gateway.do");
//            config.setEncryptType("AES");
//            config.setEncryptKey("fZ6LLZyFKJ72M2YEHPgwzA==");
//            alipayClient= new DefaultAlipayClient(config);
//        }
//    }

    @Override
    public String authOrderFreeze(OrderIdValidate orderIdValidate) {


        AlipayAuthOrderFreeze authOrderFreeze = alipayAuthOrderFreezeMapper.selectOne(new LambdaQueryWrapper<AlipayAuthOrderFreeze>().eq(AlipayAuthOrderFreeze::getOrderId,orderIdValidate.getOrderId()).orderByDesc(AlipayAuthOrderFreeze::getId).last("limit 1"));
        if(Objects.nonNull(authOrderFreeze)){
            if(authOrderFreeze.getStatus().equals(AuthStatusEnum.TO_BE_AUTHORIZED)) {
                return authOrderFreeze.getBody();
            } else if(authOrderFreeze.getStatus().equals(AuthStatusEnum.AUTHORIZATION_SUCCESSFUL)){
                Assert.state(!authOrderFreeze.getStatus().equals(AuthStatusEnum.AUTHORIZATION_SUCCESSFUL),"该订单已授权成功！");
            }
        }
        //订单
        OrderInfo orderInfo = orderInfoMapper.selectById(orderIdValidate.getOrderId());
        OrderItem orderItem = orderItemMapper.selectOne(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderIdValidate.getOrderId()).last("limit 1"));
        //租赁详情
        LeasingSchemeDetails leasingSchemeDetails = leasingSchemeDetailsMapper.selectById(orderItem.getLeasingSchemeDetailsId());
        //用户
        User user = userMapper.selectById(LikeFrontThreadLocal.getUserId());
        AlipayRoyaltyAccountInfo alipayRoyaltyAccountInfo = alipayRoyaltyAccountInfoMapper.selectById(1);
        //收款分账
        AlipayRoyaltyAccountInfo subRoyaltyAccountInfo = alipayRoyaltyAccountInfoMapper.selectOne(new LambdaQueryWrapper<AlipayRoyaltyAccountInfo>().eq(AlipayRoyaltyAccountInfo::getMerchantId, orderInfo.getDeptId()).last("limit 1"));
        if (Objects.isNull(subRoyaltyAccountInfo)) {
            subRoyaltyAccountInfo = alipayRoyaltyAccountInfoMapper.selectById(1);
        }
        //获取当前用户的风控数据
        LambdaQueryWrapper<RiskControl> riskWrapper = new LambdaQueryWrapper<>();
        riskWrapper.eq(RiskControl::getUserId, LikeFrontThreadLocal.getUserId());
        riskWrapper.last("limit 1");
        riskWrapper.orderByDesc(RiskControl::getVersion);
        RiskControl riskControl = riskControlMapper.selectOne(riskWrapper);
        Assert.notNull(riskControl, "风控数据不存在，请先上传司机信息");
        OrderFlowInfo flowInfo ;
        if(Objects.isNull(riskControl)) {
            flowInfo = saveFlowInfoLog(orderIdValidate.getOrderId(),OrderFlowTypeEnum.DEPOSIT_FREEZE, leasingSchemeDetails.getDeposit());
        }else{
            //0-10免押金，10-30，押金50%，30以上100%押金
            Assert.isTrue(riskControl.getRiskScore() > 10, "当前用户拥有免押权限，不需要进行预授权签约");
            flowInfo = saveFlowInfoLog(orderIdValidate.getOrderId(),OrderFlowTypeEnum.DEPOSIT_FREEZE, new BigDecimal(getByRiskScore(leasingSchemeDetails.getDeposit(), riskControl.getRiskScore())));
        }


        AlipayFundAuthOrderAppFreezeModel alipayFundAuthOrderAppFreezeModel = new AlipayFundAuthOrderAppFreezeModel();
        alipayFundAuthOrderAppFreezeModel.setOrderTitle(orderItem.getProductName() + "押金");
        alipayFundAuthOrderAppFreezeModel.setAmount(getByRiskScore(leasingSchemeDetails.getDeposit(), riskControl.getRiskScore()).toString());
        alipayFundAuthOrderAppFreezeModel.setPayeeUserId(alipayRoyaltyAccountInfo.getAccount());
        alipayFundAuthOrderAppFreezeModel.setOutOrderNo(CodeUtils.getFlowNo(OrderFlowTypeEnum.DEPOSIT_FREEZE));
        alipayFundAuthOrderAppFreezeModel.setOutRequestNo(flowInfo.getFlowNo());
        alipayFundAuthOrderAppFreezeModel.setProductCode("PREAUTH_PAY");

        JSONObject extraParam = new JSONObject();
        extraParam.put("secondaryMerchantId",subRoyaltyAccountInfo.getAccount());
        alipayFundAuthOrderAppFreezeModel.setExtraParam(JSONObject.toJSONString(extraParam));

        //预授权签约
        AlipayFundAuthOrderAppFreezeResponse orderAppFreezeResponse = null;
        try {
            //删除原有冻结数据
            if(Objects.nonNull(authOrderFreeze)){
                alipayAuthOrderFreezeMapper.deleteById(authOrderFreeze.getId());
            }
            notifyAuthUrl = "https://www.yixiutong.cn/rtadmin/api/notify/callback.htm";
            orderAppFreezeResponse = preAuthorizationService.aliPayFreeze(defaultAlipayClient, alipayFundAuthOrderAppFreezeModel, notifyAuthUrl);
            log.error("-----------------------------------------");
            log.info(JSON.toJSONString(orderAppFreezeResponse));

            if (orderAppFreezeResponse.isSuccess()) {
                //保存授权记录信息
                authOrderFreeze = new AlipayAuthOrderFreeze();
                authOrderFreeze.setAuthNo(orderAppFreezeResponse.getAuthNo());
                authOrderFreeze.setOrderId(orderIdValidate.getOrderId());
                authOrderFreeze.setStatus(AuthStatusEnum.TO_BE_AUTHORIZED.getCode());
                authOrderFreeze.setOutOrderNo(alipayFundAuthOrderAppFreezeModel.getOutOrderNo());
                authOrderFreeze.setAuthNo(orderAppFreezeResponse.getAuthNo());
                authOrderFreeze.setBody(orderAppFreezeResponse.getBody());
                authOrderFreeze.setOrderTitle(orderItem.getProductName());
                authOrderFreeze.setAmount(new BigDecimal(alipayFundAuthOrderAppFreezeModel.getAmount()));
                authOrderFreeze.setPayeeUserId(alipayRoyaltyAccountInfo.getAccount());
                alipayAuthOrderFreezeMapper.insert(authOrderFreeze);
            } else {
                Assert.isTrue(orderAppFreezeResponse.isSuccess(), orderAppFreezeResponse.getMsg());
            }
            return orderAppFreezeResponse.getBody();
        } catch (AlipayApiException e) {
            throw new OperateException(e.getMessage());
        }
    }

    @Override
    public Double getByRiskScore(BigDecimal price, Double riskScore) {
        if (10 <= riskScore && riskScore < 30) {
            price =  price.divide(new BigDecimal(2), 2, BigDecimal.ROUND_HALF_UP);
            ;
        } else if (10 > riskScore) {
            //免押
            price = new BigDecimal(0);
        }
        return price.doubleValue();
    }

    @Override
    public String userAgreementPageSign(OrderIdValidate orderIdValidate)  {
        AlipaySignUserAgreementRecord agreementRecord = alipaySignUserAgreementRecordMapper.selectOne(new LambdaQueryWrapper<AlipaySignUserAgreementRecord>().eq(AlipaySignUserAgreementRecord::getUserId,LikeFrontThreadLocal.getUserId()).orderByDesc(AlipaySignUserAgreementRecord::getId).last("limit 1"));
        if(Objects.nonNull(agreementRecord)){
            if(agreementRecord.getStatus().equals(AuthStatusEnum.TO_BE_AUTHORIZED)){
                return agreementRecord.getBody();
            }else if(agreementRecord.getStatus().equals(AuthStatusEnum.AUTHORIZATION_SUCCESSFUL)){
               Assert.state(!agreementRecord.getStatus().equals(AuthStatusEnum.AUTHORIZATION_SUCCESSFUL),"该订单已授权成功！");
            }
        }
        //订单
        OrderInfo orderInfo = orderInfoMapper.selectById(orderIdValidate.getOrderId());
        OrderItem orderItem = orderItemMapper.selectOne(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderIdValidate.getOrderId()).last("limit 1"));
        //租赁详情
        LeasingSchemeDetails leasingSchemeDetails = leasingSchemeDetailsMapper.selectById(orderItem.getLeasingSchemeDetailsId());
        //用户
        User user = userMapper.selectById(LikeFrontThreadLocal.getUserId());
        //授权信息
        //UserAuth userAuth = userAuthMapper.selectOne(new LambdaQueryWrapper<UserAuth>().eq(UserAuth::getUserId, user.getId()).last("limit 1"));


        //收款分账
        AlipayRoyaltyAccountInfo alipayRoyaltyAccountInfo = alipayRoyaltyAccountInfoMapper.selectOne(new LambdaQueryWrapper<AlipayRoyaltyAccountInfo>().eq(AlipayRoyaltyAccountInfo::getMerchantId, orderInfo.getDeptId()).last("limit 1"));
        if (Objects.isNull(alipayRoyaltyAccountInfo)) {
            alipayRoyaltyAccountInfo = alipayRoyaltyAccountInfoMapper.selectById(1);
        }


        AlipayUserAgreementPageSignModel alipayUserAgreementPageSignModel = new AlipayUserAgreementPageSignModel();
        //todo 此处可能需要更改
        alipayUserAgreementPageSignModel.setExternalLogonId(user.getNickname());
        alipayUserAgreementPageSignModel.setPersonalProductCode("GENERAL_WITHHOLDING_P");
        alipayUserAgreementPageSignModel.setProductCode("GENERAL_WITHHOLDING");
        alipayUserAgreementPageSignModel.setSignScene("INDUSTRY|CARRENTAL");

        /*
          渠道信息
         */
        AccessParams accessParams = new AccessParams();
        accessParams.setChannel("ALIPAYAPP");
        alipayUserAgreementPageSignModel.setAccessParams(accessParams);
        /*
          二级商户信息
         */
        SubMerchantParams subMerchantParams = new SubMerchantParams();
        subMerchantParams.setSubMerchantId(alipayRoyaltyAccountInfo.getAccount());
        subMerchantParams.setSubMerchantName(alipayRoyaltyAccountInfo.getName());
        subMerchantParams.setSubMerchantServiceName("租金代扣");
        alipayUserAgreementPageSignModel.setSubMerchant(subMerchantParams);


 //       PeriodRuleParams periodRuleParams = new PeriodRuleParams();
//        periodRuleParams.setPeriodType("DAY");
//        periodRuleParams.setPeriod(365L);
//        periodRuleParams.setExecuteTime(TimeUtils.yyyyMMddFormat(LocalDate.now().plusDays(1)));
//        periodRuleParams.setSingleAmount(leasingSchemeDetails.getAmountPeriod().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
//        alipayUserAgreementPageSignModel.setPeriodRuleParams(periodRuleParams);

        /*
          用户信息（非必填 ，暂时取消）
         */
//        IdentityParams identityParams = new IdentityParams();
//        identityParams.setSignUserId(userAuth.getAlipayUserid());
//        identityParams.setIdentityHash(AlipayUtils.getSHA256(user.getRealName()+user.getCardNo()));
//        identityParams.setUserName(user.getRealName());
//        identityParams.setCertNo(user.getCardNo());
//        alipayUserAgreementPageSignModel.setIdentityParams(identityParams);


        try{
            //签约代扣
            AlipayUserAgreementPageSignResponse
                    alipayUserAgreementPageSignResponse = userAgreementService.userAgreementSign(defaultAlipayClient, alipayUserAgreementPageSignModel, notifyAgreementUrl);
            //判断代扣签约是否正常，成功保存代扣签约记录
            if (alipayUserAgreementPageSignResponse.isSuccess()) {
                //删除原有签约数据
                if(Objects.nonNull(agreementRecord)){
                    alipaySignUserAgreementRecordMapper.deleteById(agreementRecord.getId());
                }
                saveFlowInfoLog(orderIdValidate.getOrderId(),OrderFlowTypeEnum.AGREEMENT_RECORD_SIGN, null);

                agreementRecord = new AlipaySignUserAgreementRecord();
                agreementRecord.setOrderId(orderIdValidate.getOrderId());
                agreementRecord.setStatus(AuthStatusEnum.TO_BE_AUTHORIZED.getCode());
                agreementRecord.setBody( alipayUserAgreementPageSignResponse.getBody());
                agreementRecord.setUserId(LikeFrontThreadLocal.getUserId().longValue());

                alipaySignUserAgreementRecordMapper.insert(agreementRecord);
            } else {
                Assert.isTrue(alipayUserAgreementPageSignResponse.isSuccess(), alipayUserAgreementPageSignResponse.getMsg());
            }
            return URLEncoder.encode(alipayUserAgreementPageSignResponse.getBody(), "UTF-8");
        } catch (AlipayApiException e) {
            throw new OperateException(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public UserSignVo getSignStatus(OrderIdValidate orderIdValidate){
        UserSignVo userSignVo = new UserSignVo();
        //是否需冻结押金
        //获取当前用户的风控数据
        LambdaQueryWrapper<RiskControl> riskWrapper = new LambdaQueryWrapper<>();
        riskWrapper.eq(RiskControl::getUserId, LikeFrontThreadLocal.getUserId());
        riskWrapper.last("limit 1");
        riskWrapper.orderByDesc(RiskControl::getVersion);
        RiskControl riskControl = riskControlMapper.selectOne(riskWrapper);
        Assert.notNull(riskControl, "风控数据不存在，请先上传司机信息");

        //押金冻结
        AlipayAuthOrderFreeze authOrderFreeze = alipayAuthOrderFreezeMapper.selectOne(new LambdaQueryWrapper<AlipayAuthOrderFreeze>().eq(AlipayAuthOrderFreeze::getOrderId,orderIdValidate.getOrderId()).orderByDesc(AlipayAuthOrderFreeze::getId).last("limit 1"));
        AlipayAuthOrderFreezeVo alipayAuthOrderFreezeVo = new AlipayAuthOrderFreezeVo();
        if(Objects.nonNull(authOrderFreeze)){
            BeanUtil.copyProperties(authOrderFreeze,alipayAuthOrderFreezeVo);
        }
        userSignVo.setAlipayAuthOrderFreeze(alipayAuthOrderFreezeVo);


        //0-10免押金，10-30，押金50%，30以上100%押金
       if(riskControl.getRiskScore()<10){
           //查询是否存在正在进行中的免押订单(非当前订单)
           Integer count = orderInfoMapper.countZeroDepositOrder(orderIdValidate.getOrderId(),LikeFrontThreadLocal.getUserId());
           if(count>0) {
               userSignVo.setNeedDepositFreeze(true);
           }else {
               //查询当前订单是否已冻结押金
              if(Objects.isNull(authOrderFreeze)){
                  userSignVo.setNeedDepositFreeze(false);
              }else {
                  userSignVo.setNeedDepositFreeze(true);
              }
           }
       }else {
           //获取当前订单是否已经冻结了押金
           List<AlipayAuthOrderFreeze> alipayAuthOrderFreezeList = alipayAuthOrderFreezeMapper.selectList(new LambdaQueryWrapper<AlipayAuthOrderFreeze>()
                   .eq(AlipayAuthOrderFreeze::getOrderId, orderIdValidate.getOrderId()).eq(AlipayAuthOrderFreeze::getStatus, FundAuthFreezeStatus.FUND_AUTH_FREEZE.getCode()));
           if (Objects.isNull(alipayAuthOrderFreezeList) || alipayAuthOrderFreezeList.isEmpty()) {
               userSignVo.setNeedDepositFreeze(true);
           } else {
               userSignVo.setNeedDepositFreeze(false);
           }
       }

       //代扣签约
        LambdaQueryWrapper<AlipaySignUserAgreementRecord> signQueryWrapper =  new LambdaQueryWrapper<>();
        signQueryWrapper.eq(AlipaySignUserAgreementRecord::getUserId,LikeFrontThreadLocal.getUserId())
                .orderByDesc(AlipaySignUserAgreementRecord::getId).last("limit 1");
        AlipaySignUserAgreementRecord agreementRecord = alipaySignUserAgreementRecordMapper.selectOne(signQueryWrapper);
        AlipaySignUserAgreementRecordVo alipaySignUserAgreementRecordVo =new AlipaySignUserAgreementRecordVo();
        if(Objects.nonNull(agreementRecord)&& agreementRecord.getStatus().equals(AuthStatusEnum.AUTHORIZATION_SUCCESSFUL.getCode())) {
            BeanUtil.copyProperties(agreementRecord,alipaySignUserAgreementRecordVo);
            userSignVo.setNeedSignUser(false);
        }else{
            userSignVo.setNeedSignUser(true);
        }
        userSignVo.setAlipaySignUserAgreementRecord(alipaySignUserAgreementRecordVo);
        return userSignVo;
    }

    @Override
    public void cancelAuthOrderFreeze(Long orderId) throws AlipayApiException {
        AlipayAuthOrderFreeze alipayAuthOrderFreeze = alipayAuthOrderFreezeMapper.selectOne(new LambdaQueryWrapper<AlipayAuthOrderFreeze>().eq(AlipayAuthOrderFreeze::getOrderId,orderId).orderByDesc(AlipayAuthOrderFreeze::getId).last("limit 1"));
        //Assert.notNull(alipayAuthOrderFreeze,"押金冻结记录不存在！");
        if(Objects.isNull(alipayAuthOrderFreeze)){
            return;
        }
        //Assert.isTrue(alipayAuthOrderFreeze.getStatus().equals(FUND_AUTH_FREEZE.getCode()),"当前状态不能进行押金解冻操作！");
        OrderFlowInfo orderFlowInfo = saveFlowInfoLog(orderId,OrderFlowTypeEnum.CANCEL_DEPOSIT_FREEZE,alipayAuthOrderFreeze.getAmount());

        AlipayFundAuthOrderUnfreezeModel alipayFundAuthOrderUnfreezeModel =new AlipayFundAuthOrderUnfreezeModel();
        alipayFundAuthOrderUnfreezeModel.setAuthNo(alipayAuthOrderFreeze.getAuthNo());
        alipayFundAuthOrderUnfreezeModel.setAmount(alipayAuthOrderFreeze.getAmount().toString());
        alipayFundAuthOrderUnfreezeModel.setOutRequestNo(orderFlowInfo.getFlowNo());
        alipayFundAuthOrderUnfreezeModel.setRemark("解冻押金");
        //取消授权
        preAuthorizationService.unfreeze(defaultAlipayClient,alipayFundAuthOrderUnfreezeModel);
        alipayAuthOrderFreeze.setStatus(FUND_AUTH_UNFREEZE.getCode());
        alipayAuthOrderFreezeMapper.updateById(alipayAuthOrderFreeze);
    }

    @Override
    public void cancelUserAgreementRecord(Long orderId) throws AlipayApiException {
        AlipaySignUserAgreementRecord agreementRecord = alipaySignUserAgreementRecordMapper.selectOne(new LambdaQueryWrapper<AlipaySignUserAgreementRecord>().eq(AlipaySignUserAgreementRecord::getOrderId,orderId).orderByDesc(AlipaySignUserAgreementRecord::getId).last("limit 1"));

        if(Objects.nonNull(agreementRecord)&& agreementRecord.getStatus().equals(1)){
           saveFlowInfoLog(orderId,OrderFlowTypeEnum.CANCEL_AGREEMENT_RECORD_SIGN, null);

            AlipayUserAgreementUnsignModel alipayUserAgreementUnsignModel = new AlipayUserAgreementUnsignModel();
            alipayUserAgreementUnsignModel.setAgreementNo(agreementRecord.getAgreementNo());
            //取消授权
            userAgreementService.userAgreementUnsign(defaultAlipayClient,alipayUserAgreementUnsignModel);
        }

     }


    @Override
    public AlipayFundAuthOperationDetailQueryResponse queryAuthOrderFreeze(Long orderId) throws AlipayApiException {
        AlipayAuthOrderFreeze alipayAuthOrderFreeze = alipayAuthOrderFreezeMapper.selectOne(new LambdaQueryWrapper<AlipayAuthOrderFreeze>().eq(AlipayAuthOrderFreeze::getOrderId,orderId).orderByDesc(AlipayAuthOrderFreeze::getId).last("limit 1"));
        Assert.notNull(alipayAuthOrderFreeze,"押金冻结记录不存在！");
        OrderFlowInfo orderFlowInfo = saveFlowInfoLog(orderId,OrderFlowTypeEnum.CANCEL_DEPOSIT_FREEZE,alipayAuthOrderFreeze.getAmount());

        AlipayFundAuthOperationDetailQueryModel alipayFundAuthOperationDetailQueryModel =new AlipayFundAuthOperationDetailQueryModel();
        alipayFundAuthOperationDetailQueryModel.setOutOrderNo(alipayAuthOrderFreeze.getOutOrderNo());
        alipayFundAuthOperationDetailQueryModel.setOutRequestNo(alipayAuthOrderFreeze.getOutRequestNo());
        //取消授权
        AlipayFundAuthOperationDetailQueryResponse alipayFundAuthOperationDetailQueryResponse =preAuthorizationService.authQuery(defaultAlipayClient,alipayFundAuthOperationDetailQueryModel);
        return alipayFundAuthOperationDetailQueryResponse;
    }

    /**
     * 流水日志
     * @param orderId
     * @param orderFlowTypeEnum
     * @param amount
     * @return
     */
        @Override
        public   OrderFlowInfo saveFlowInfoLog(Long orderId, OrderFlowTypeEnum orderFlowTypeEnum, BigDecimal amount){
            OrderFlowInfo orderFlowInfo =   new OrderFlowInfo();
            orderFlowInfo.setFlowNo(CodeUtils.getFlowNo(orderFlowTypeEnum));
            orderFlowInfo.setAmount(amount);
            orderFlowInfo.setOrderid(orderId);
            orderFlowInfo.setType(orderFlowTypeEnum.getCode());
            orderFlowInfo.setItemName(orderFlowTypeEnum.getMsg());
            orderFlowInfo.setSourceAppId(0);
            orderFlowInfoMapper.insert(orderFlowInfo);
            return orderFlowInfo;
        }
}
